jQuery(function($){
	var boundx,boundy,
        // Grab some information about the preview pane
	$preview = $('#preview-pane'),
	$pcnt = $('#preview-pane .preview-container'),
	$pimg = $('#preview-pane .preview-container img'),

	xsize = $pcnt.width(), //预览区宽
	ysize = $pcnt.height(), //预览区高
	selectWidth = 600, //选中区域宽度
	selectHeight = 600; //选中区域高度
    var jcrop_api;
    // 参数参考 http://code.ciaoca.com/jquery/jcrop/--%>
	function initImg(){
    	if(jcrop_api){
    		jcrop_api.destroy();
    	}
    	boundx= $("#target").width(); //原图片宽
    	boundy= $("#target").height(); //原图片高
    	selectWidth = $("#setwidth").val();
		selectHeight = $("#setheight").val();
	    $('#target').Jcrop({
			// start off with jcrop-light class
	      	bgOpacity: 0.5,
	      	bgColor: 'black',
	      	addClass: 'jcrop-dark',
	      	aspectRatio: selectWidth/selectHeight, //选框宽高比。说明：width/height
	      	onChange : function(coords){
	      		setTimeout(function() {
	    			updatePreview(coords);
	    		}, 1); //延时，否则新上传图片的长宽值不对
				var coordsw = coords.w.toFixed(0);
				var coordsh = coords.h.toFixed(0);
				$('#x').val(coords.x);
	    		$('#y').val(coords.y);
	    		$('#x2').val(coords.x2);
	    		$('#y2').val(coords.y2);
	    		$('#w').val(coordsw);
	    		$('#h').val(coordsh);
	    		$(".wshow").text(coordsw);
	    		$(".hshow").text(coordsh);
	      	}
	    }, function(){
	      	jcrop_api = this;
	      	jcrop_api.setSelect([0, 0, selectWidth, selectHeight]); //超过图片宽度时，按图片最大宽度或高度显示
	      	jcrop_api.setOptions({ bgFade: true });
	      	jcrop_api.ui.selection.addClass('jcrop-selection');
	      	var bounds = jcrop_api.getBounds(); //获取图片实际尺寸，格式为：[w, h]
	        boundx = bounds[0];
	        boundy = bounds[1];
	      	$preview.appendTo(jcrop_api.ui.holder);
	    });
    }
	initImg();
    // 预览
    function updatePreview(c){
		if (parseInt(c.w) > 0){
	        var rx = xsize / c.w; //rx=ry,为缩放比例
	        var ry = ysize / c.h;
	        $pimg.css({
				width: Math.round(rx * boundx) + 'px',
				height: Math.round(ry * boundy) + 'px',
				marginLeft: '-' + Math.round(rx * c.x) + 'px',
				marginTop: '-' + Math.round(ry * c.y) + 'px'
	        });
		}
	};
	
	// 调用AjaxUpload的上传组件
	var initUpload = function(ele, actionUrl, name, callback) {
		var _default = {  		//默认配置参数
				'name' : 'file',   //上传时流的文件名称
				'fileType' : 'images',  //上传 类型     目前可选参数   (images:图片 ,file:文件)
				'exts' : 'jpg|png|bmp|jpeg|gif|JPG|PNG|BMP|GIF|JPEG', //上传文件的后缀 限制  自定义
				'uploadURL' : actionUrl, //上传的路径     详情见mytags.jsp  有默认参数
				'uploadButton' : '#uploadButton', //需要绑定上传的按钮，建议用id参数
				'fileNumber' : 1 // 默认限制1个
			};
		var options =  _default;

		var parE = ele.closest(".uploadContainer");
		if (parE.length == 0) {
			parE = ele.parent();
		}

		var filePathE = parE.find(".imgPath");
		 var listE = parE.find(".img"); //新上传的
		new AjaxUpload(ele, {
			// 文件上传地址 action
			// ://http://upload.credithegs.gov.cn/affixUpload?callback=http://localhost:8081/uploadCallback&serverLocation=&type=2
			// 图片上传你地址 action : settings.uploadUeRootPath +
			// "?action=uploadimage&sendRedirect=" + ctxPath + "/" +
			// settings.uploadCallbackURL,
			action : options.uploadURL,
			name : options.name,
			onSubmit : function(file, ext) {
				if ("images" == options.fileType) {
					if (options.exts != "*") {
						if (ext && new RegExp("^(" + options.exts + ")$").test(ext)) {
							this.setData({
								'info' : '文件类型为图片'
							});
						} else {
							// alert()
							alert('文件格式错误，请上传格式为' + options.exts + ' 的图片',);
							return false;
						}
					}
				} else if ("file" == options.fileType) {
					if (options.exts != "*") {
						if (ext && new RegExp("^(" + options.exts + ")$").test(ext)) {
							this.setData({
								'info' : '文件类型'
							});
						} else {
							alert('文件格式错误，请上传格式为' + options.exts + '的文件');
							return false;
						}
					}
				} else {
					alert('fileType参数错误！');
					return false;
				}
				this.disable();

			},
			onComplete : function(file, response) {
				var response = $.parseJSON(response); //返回的response为字符串重新处理为json
				callback(response);
				this.enable();
			}
		});
		
		
	};
	var formE = $(".container");
	// 上传图片
	var initImgUpload = function() {
		var imgUploadHandle = formE.find('.imgUploadHandle');
		if (imgUploadHandle.length > 0) {
			//var actionUrl = uploadBaseUrl + '/common/uploadtemp' + uploadCallbackURL;
			var actionUrl = uploadBaseUrl+'/tool/uploadtemp?sendRedirect='+uploadCallbackURL + '&uploadGroup='+uploadGroup; //上传的路径 
			imgUploadHandle.each(function() {
				var $this = $(this);
				initUpload($this, actionUrl, 'imgSource', function(response) {
					if (response && response.success) {
						/* 返回json格式，格式{"error":0,"url":"http:\/\/test.11315.com\/imagesUp\/2016\/09\/19\/po77w.jpg"} */
						var imageSrc = response.url;
						formE.find('#target').css({"width":"","height":""});
						formE.find('#target').attr('src', imageSrc);
						formE.find('#preview').attr('src', imageSrc);
						formE.find('#imgSource').val(imageSrc).triggerHandler("change");//触发自定义change事件
						initImg();
						formE.find(".submitbtn").show();
                    }else{
                    	alert(response.message)
                    }
				});
			});
		}
	};
	// 上传图片
	initImgUpload();
	
	//裁剪
	var submitEdit = formE.find(".submitbtn");
	if (submitEdit.length > 0) {
		submitEdit.click(function() {
			var $this = $(this);
			var imgPath = formE.find("#imgSource").val();
			if (imgPath) {
				$.getJSON(uploadBaseUrl + '/tool/imgcut?callback=?', formE.find(":input").serialize(), function(data) {
					alert(data.message);
					if(!data.err){
						formE.find("#cutresult").html("<a class='downloadfile' href='"+uploadBaseUrl+'/tool/downloadfile?path=' + data.value+"'>下载图片</a>");
					}
				});
			} else {
				alert("图片未上传！");
			}
		});
	}
	
	$("#setwidth,#setheight").change(function(){
		var pheight = 250 * $("#setheight").val() / $("#setwidth").val();
		pheight = pheight.toFixed(0);
		$pcnt.height(pheight);
		boundx= $("#target").width();
		boundy= $("#target").height();
		xsize = $pcnt.width();
		ysize = $pcnt.height();
		initImg();
	});
});